# This is a sample Python script.
import random
import time
from copy import deepcopy
from datetime import datetime

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import cv2 as cv
import numpy as np
import virtualvideo
from PIL import Image, ImageFont, ImageDraw

colors = [
    (0xf5, 0xde, 0xb3),  # 未走过的路
    (0x8a, 0x2b, 0xe2),  # 墙壁
    (0xd3, 0xdb, 0x64),  # 当前位置
    (0x12, 0x8b, 0x37),  # 走过
    (0x32, 0x12, 0x8b),  # 重复经过
    (0xff, 0x00, 0x00),
    (0xff, 0x00, 0x00),
    (0xff, 0x00, 0x00),
    (0xff, 0x00, 0x00),
    (0xc4, 0xc4, 0xc4),  # 迷雾
    (0xff, 0x00, 0x00),
    (0x00, 0xff, 0xff),
    (0xff, 0xff, 0x00),
]


class MyVideoSource(virtualvideo.VideoSource):
    def __init__(self):
        self.img = np.full((41, 41, 3), (0xe2, 0x2b, 0x8a), dtype=np.uint8)
        self.background = np.full((738, 1312, 3), 255, dtype=np.uint8)
        self.text_bg = np.full((738, (1312 - 738), 3), 255, dtype=np.uint8)
        self.font = ImageFont.truetype("noto/NotoSansCJK-Bold.ttc", 24)
        self._scale = 18
        size = self.img.shape
        # opencv's shape is y,x,channels
        self._size = (1312, 738)
        self.initTime = time.time()
        self.last_frame = self.img
        self.last_text = None
        self.frame_count = 0
        self.origin_maze = None
        self.generating = False

    def img_size(self):
        return self._size

    def fps(self):
        return 60

    def tips(self, img, position, line1, line2=None, line3=None, line4=None):
        imgPIL = Image.fromarray(cv.cvtColor(img, cv.COLOR_BGR2RGB))
        draw = ImageDraw.Draw(imgPIL)
        draw.text(position, line1, font=self.font, fill=(160, 255, 100))
        if line2 is not None:
            draw.text((41, 41 * 2), line2, font=self.font, fill=(128, 0, 128))
        if line3 is not None:
            draw.text((41, 41 * 3), line3, font=self.font, fill=(207, 207, 196))
        if line4 is not None:
            draw.text((41, 41 * 4), line4, font=self.font, fill=(207, 207, 196))
        del draw
        return cv.cvtColor(np.asarray(imgPIL), cv.COLOR_RGB2BGR)

    def generator(self):
        # 计算实时的帧率
        start_time = time.time()
        while True:
            for i in range(25):
                frame = self.img
                text = np.copy(self.text_bg)
                continueTime = time.time() - self.initTime

                x = random.randint(1, 39)
                y = random.randint(1, 39)
                frame[x, y] += 1

                text = self.tips(
                    text,
                    (41, 41),
                    "测试ffmpeg是否因为多线程导致堵塞",
                    datetime.now().strftime("%X"),
                    "+" + str(int(continueTime)) + "s"
                )

                try:
                    # 放大到定义尺寸 16 : 9
                    frame = cv.resize(frame, (41 * self._scale, 41 * self._scale), interpolation=cv.INTER_NEAREST)
                    self.background[0:41 * self._scale, 0:41 * self._scale, :] = frame
                    self.background[0:41 * self._scale, 41 * self._scale:1312, :] = text

                    # 寻路的时候, 显示生成的完整迷宫
                    if not self.generating and self.origin_maze is not None:
                        resized_origin_maze = cv.resize(self.origin_maze, (41 * 3, 41 * 3),
                                                        interpolation=cv.INTER_NEAREST)
                        y1 = 41 * self._scale - 41 * 4
                        y2 = 41 * self._scale - 41
                        x1 = 41 * self._scale + int((1312 - 41 * (self._scale + 3)) / 2)
                        x2 = x1 + 41 * 3
                        self.background[y1:y2, x1:x2, :] = resized_origin_maze
                        del resized_origin_maze

                    if self.background is None:
                        print("background is None")

                    yield self.background
                except Exception as e:
                    print(e)
                    pass

                start_time = time.time()

                # 单位是秒, 如果设置为1, 则等待1秒, 这样会影响视频帧率, 1秒1帧
                time.sleep(0.016)


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.

    vidsrc = MyVideoSource()
    fvd = virtualvideo.FakeVideoDevice()
    fvd.init_input(vidsrc)
    fvd.init_output(2, 1280, 720, fps=60)
    fvd.run(quiet=True)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
